package org.filecollector.msgcontroller.answers.converters;

import com.google.gson.*;
import org.filecollector.msgcontroller.answers.AnswerMessage;
import org.filecollector.msgcontroller.answers.responsecodes.CodeConvertDictionary;

import java.lang.reflect.Type;

public class AnswerConverter implements JsonSerializer<AnswerMessage>, JsonDeserializer<AnswerMessage> {

    @Override
    public AnswerMessage deserialize(
            JsonElement jsonElement,
            Type type,
            JsonDeserializationContext jsonDeserializationContext
    ) throws JsonParseException {
        JsonObject object = jsonElement.getAsJsonObject();
        return new AnswerMessage(
                CodeConvertDictionary.get(object.get("code").getAsInt()),
                object.get("uri").getAsString(),
                object.get("data").getAsString()
        );
    }

    @Override
    public JsonElement serialize(
            AnswerMessage message,
            Type type,
            JsonSerializationContext jsonSerializationContext
    ) {
        JsonObject object = new JsonObject();
        object.addProperty("code", CodeConvertDictionary.get(message.code()));
        object.addProperty("uri", message.seeOtherURI());
        object.addProperty("data", message.data());
        return object;
    }
}
